package SV_HASH_NO_SALT;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class Vulnerable {
    /*
     * Adds a new user; stores login and password hash.
     */

    private Map<String, String> userStore = new HashMap<>();
    public void addUser(String login, byte[] password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");









            md.update(password); // < -- calculate hash for the password









            byte[] hash = md.digest();
            storeHashString(login, Hex.encodeHexString(hash));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }
    }

    private void storeHashString(String login, String hashString) {
        // 在这里实现您的存储逻辑，例如将用户名和哈希密码存储到数据库或文件中
        userStore.put(login, hashString);
        System.out.println("User " + login + " stored with hash: " + hashString);
    }

    /*
     * Validates user login information. Returns true if user exists, and
       entered password hash matches stored password hash;
     * otherwise returns false.
     */
    public boolean login(String login, byte[] password) {
        try {
            String storedHash = readHashString(login);
            if (storedHash != null) {
                MessageDigest md = MessageDigest.getInstance("MD5");









                md.update(password); // < -- calculate hash for the password









                byte[] hash = md.digest();
                return MessageDigest.isEqual(hash, Hex.decodeHex(storedHash.toCharArray()));
            } else {
                return false;
            }
        } catch (NoSuchAlgorithmException | DecoderException e) {
            throw new IllegalStateException(e);
        }
    }

    private String readHashString(String login) {
        return null;
    }

}
